package com.example.springsecurityoauthdemo.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @RequestMapping(value = "/login-success", produces = {"text/plain;charset=UTF-8"})
    public String hello(){
        return "登录成果";
    }

    @GetMapping("/r/r1")
    public String r1(){
        return getCurrentUserName()+"访问资源1";
    }

    @GetMapping("/r/r2")
    public String r2(){
        return getCurrentUserName()+"访问资源2";
    }
    @GetMapping("/r/r3")
    @PreAuthorize("hasAnyAuthority('update')")
    public String r3(){
        return getCurrentUserName()+"访问资源3  update";
    }

    private String getCurrentUserName(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal==null){
            return "匿名";
        }
        if (principal instanceof UserDetails){
            UserDetails u = (UserDetails)principal;
            return u.getUsername();
        }else{
            return principal.toString();
        }
    }
}
